﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Text.RegularExpressions;
using System.Text;
using UnityEngine.UI;
using Michsky.UI.ModernUIPack;
using AoyouzheStudio;
using System.IO;
using DG.Tweening;
using Microsoft.International.Converters.PinYinConverter;

public class MainController : MonoBehaviour
{
    private TMP_InputField researhName, setScore, setScoreReason;
    private string researchStrTemp = string.Empty, setScoreStrTemp = string.Empty, setScoreStrReason = string.Empty;

    private Button setScoreButton, researchOwnInfo;

    private ModalWindowManager researchOwnInfoPanel;
    private TMP_Text researchOwnInfoPanel_Title;
    private ModalWindowTabs researchOwnInfo_Tabs;

    private OwnInfoManager ownInfoManager;

    private int i;

    private Button aboutApp, aboutClose;

    private GameObject aboutPanel;

    private OwnInfo ownInfo;

    private Button lookDontOriginalScoreInfo, lookDontOriginalScoreInfoClose;
    private GameObject lookDontOriginalScoreInfoPanel;
    private TMP_Text lookDontOriginalScoreInfoPanelText;

    public static string _startPath;

    private Toast toast;

    private TMP_Text version;

    private ButtonManager quit;

    private int quitCount;

    private void Awake()
    {
        researhName = transform.Find("CenterColumn/One/NameField").GetComponent<TMP_InputField>();
        setScore = transform.Find("CenterColumn/Two/NameField").GetComponent<TMP_InputField>();
        setScoreReason = transform.Find("CenterColumn/Three/NameField").GetComponent<TMP_InputField>();

        setScoreButton = transform.Find("CenterColumn/Three/AffrimScore").GetComponent<Button>();
        researchOwnInfo = transform.Find("CenterColumn/Three/ResearchOwnInfo").GetComponent<Button>();

        researchOwnInfoPanel = transform.Find("ResearchOwnInfoPanel").GetComponent<ModalWindowManager>();
        researchOwnInfoPanel_Title = researchOwnInfoPanel.transform.Find("Content/Title Bar/Title").GetComponent<TMP_Text>();
        researchOwnInfo_Tabs = transform.Find("ResearchOwnInfoPanel/Content/Tabs").GetComponent<ModalWindowTabs>();

        ownInfoManager = GameObject.Find("OwnInfoManager").GetComponent<OwnInfoManager>();


        aboutApp = transform.Find("DownColumn/AboutApp").GetComponent<Button>();
        aboutPanel = transform.Find("AboutPanel").gameObject;
        aboutClose = aboutPanel.transform.Find("Top/Close").GetComponent<Button>();

        lookDontOriginalScoreInfoPanel = transform.Find("LookDontOriginalScoreInfoPanel").gameObject;
        lookDontOriginalScoreInfo = transform.Find("CenterColumn/Three/LookDontOriginalScoreInfo").GetComponent<Button>();
        lookDontOriginalScoreInfoClose = lookDontOriginalScoreInfoPanel.transform.Find("Top/Close").GetComponent<Button>();
        lookDontOriginalScoreInfoPanelText = lookDontOriginalScoreInfoPanel.transform.Find("Viewport/Content/Text").GetComponent<TMP_Text>();

        toast = GameObject.Find("/OriginalAndroid").GetComponent<Toast>();

        version = transform.Find("DownColumn/Version").GetComponent<TMP_Text>();

        quit = transform.Find("DownColumn/Quit").GetComponent<ButtonManager>();

        if (Platform() == RuntimePlatform.WindowsEditor) _startPath = Application.streamingAssetsPath;
        else if (Platform() == RuntimePlatform.Android) _startPath = Application.persistentDataPath;
    }

    public void Start()
    {
        AddEventListener();
        CheckCreateRootDirectory();

        toast.InvokeEvent("欢迎使用千分制app");
        version.text = $"version:{Application.version}";

        quit.buttonEvent.AddListener(() => {
            StartCoroutine(Quit());
        });
    }

    private void CheckCreateRootDirectory()
    {
        if (!DirectoryExist("/Persion"))
            Directory.CreateDirectory(_startPath + "/Persion");
        if (!DirectoryExist("/PersionInfos"))
            Directory.CreateDirectory(_startPath + "/PersionInfos");
    }



    /// <summary>
    /// 监听事件
    /// </summary>
    private void AddEventListener()
    {
        researhName.onEndEdit.AddListener(OnEndEditCheckResearchName);
        setScore.onEndEdit.AddListener(OnEndEditCheckSetScore);
        setScoreReason.onValueChanged.AddListener(OnChangeCheckSetScoreReason);

        setScoreButton.onClick.AddListener(() => {
            if (researchStrTemp != string.Empty && setScoreStrTemp != string.Empty && setScoreStrReason != string.Empty)
            {
                ownInfo = new OwnInfo();
                if (FileExist($"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json"))
                {
                    ownInfo.score = JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score + int.Parse(setScoreStrTemp);
                    Debug.Log(ownInfo.score);
                }
                else
                {
                    ownInfo.score = 800 + int.Parse(setScoreStrTemp);
                }

                ownInfo.score = Mathf.Clamp(ownInfo.score, 0, 1000);


                JsonTool.GetInstance().Write(ownInfo, _startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json");


                string _data = string.Empty;
                if (FileExist($"/Persion/{ConvertToPinYin(researchStrTemp)}.txt"))
                {
                    _data = ownInfoManager.InvokeEvent(InfoType.Read, _startPath + $"/Persion/{ConvertToPinYin(researchStrTemp)}.txt", null);
                }
                ownInfoManager.InvokeEvent(InfoType.Write, _startPath + $"/Persion/{ConvertToPinYin(researchStrTemp)}.txt", _data.Insert(0, $"{System.DateTime.Now} 加减分数:{setScoreStrTemp}\n原因：{setScoreStrReason}\n"));

                //记录不为800分的学生记录
                if (ownInfo.score != 800)
                {
                    WriteDontOriginalScoresInfo("/DontOriginalScoresInfo.txt");
                }


                //检测是否存在 以前为800分，现在不是的
                WriteBeforeDontOriginalScoresNowChangedInfo("/DontOriginalScoresInfo.txt");

                //清空加扣分数和加扣分数原因inputfield
                setScore.text = string.Empty;
                setScoreReason.text = string.Empty;
            }
            else
            {
                Debug.Log("this is null");
                //此处加入toast android原生方法
                toast.InvokeEvent("请确保所有输入框内容不为空！");
            }

        });

        researchOwnInfo.onClick.AddListener(() => {
            if (researhName.text != string.Empty)
            {
                if (!FileExist($"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json"))
                {
                    ownInfo = new OwnInfo();
                    JsonTool.GetInstance().Write(ownInfo, _startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json");
                }
                researchOwnInfoPanel_Title.text = $"{researchStrTemp}的个人加扣分记录\n\t当前分数：<color=#FF6666>{JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score}</color>";

                researchOwnInfoPanel.OpenWindow();
                LoadOwnPanelData();
            }
            else
            {
                //此处加入toast android原生方法
                toast.InvokeEvent("请确保名字不为空！");
            }
        });

        aboutApp.onClick.AddListener(() => {
            QuitCountDefault();
            aboutPanel.SetActive(true);
            aboutPanel.GetComponent<CanvasGroup>()
            .DOFade(1.0f, .35f)
            .SetEase(Ease.InOutExpo);
            aboutPanel.transform
            .DOLocalMoveX(.0f, .35f);
        });

        aboutClose.onClick.AddListener(AboutClose);


        lookDontOriginalScoreInfo.onClick.AddListener(() => {
            QuitCountDefault();
            lookDontOriginalScoreInfoPanel.SetActive(true);
            lookDontOriginalScoreInfoPanel.GetComponent<CanvasGroup>()
            .DOFade(1.0f, .35f)
            .SetEase(Ease.InOutExpo);
            lookDontOriginalScoreInfoPanel.transform
            .DOLocalMoveX(.0f, .35f);

            if(FileExist("/DontOriginalScoresInfo.txt"))
                lookDontOriginalScoreInfoPanelText.text = File.ReadAllText(_startPath + "/DontOriginalScoresInfo.txt");
        });

        lookDontOriginalScoreInfoClose.onClick.AddListener(LookDontOriginalScoreInfoClose);
    }

    private void Update()
    {
        ReturnLinstener();
    }


    #region Research own info panel model.


    private void LoadOwnPanelData()
    {
        researchOwnInfo_Tabs.currentPanelIndex = 0;

        if (FileExist($"/Persion/{ConvertToPinYin(researchStrTemp)}.txt"))
        {
            string _data = ownInfoManager.InvokeEvent(InfoType.Read, _startPath + $"/Persion/{ConvertToPinYin(researchStrTemp)}.txt", null);
            string[] _dataByLine = _data.Split('\n');
            int _lines = _dataByLine.Length;
            TMP_Text _textComponent = null;

            for (i = 0; i < _lines; i++)
            {
                if (i < 4 * 6)
                {
                    _textComponent = researchOwnInfo_Tabs.panels[i / 6].transform.Find("Text").GetComponent<TMP_Text>();
                    _dataByLine[i] += "\n";


                    if (i % 6 == 0 && _dataByLine[i] != "\n")
                        _textComponent.text = string.Empty;

                    _textComponent.text += _dataByLine[i];
                }
            }
        }
        else
        {
            //此处加入toast android原生方法
            toast.InvokeEvent("个人信息为空！");
        }

    }


    #endregion;



    #region Check inputfield


    private void OnEndEditCheckResearchName(string value)
    {
        Regex rg = new Regex(@"^[\u4e00-\u9fa5]{0,}$");
        if (rg.IsMatch(value) && (GetStrLength(value) == 6 || GetStrLength(value) == 4))
        {
            //正确比配
            Debug.Log("当前搜索名字正确匹配");
            researchStrTemp = value;
        }
        else
        {
            researhName.text = researchStrTemp;
            //匹配错误，有非汉字字符串
            //此处加入toast android原生方法
            toast.InvokeEvent("名字格式错误！");
        }
    }


    private void OnEndEditCheckSetScore(string value)
    {
        Regex _regex = new Regex(@"^[\-|0-9][0-9]*");
        Regex _regex_2 = new Regex(@"^[\-|0-9][0-9]{1,}$");
        int _outTemp = 0;
        if ((_regex.IsMatch(value) || _regex_2.IsMatch(value)) && int.TryParse(value, out _outTemp))
        {
            int _score = 0;

            _score = Mathf.Clamp(int.Parse(value), -1000, 1000);
            setScore.text = _score.ToString();
            setScoreStrTemp = value;
            Debug.Log($"当前设置分数正确匹配:{_score}");
        }
        else
        {
            setScore.text = setScoreStrTemp;
            //此处加入toast android原生方法
            toast.InvokeEvent("分数格式错误！");
        }
    }


    private void OnChangeCheckSetScoreReason(string value)
    {
        if (GetStrLength(value) <= 20)
        {
            setScoreStrReason = value;
        }
        else
        {
            setScoreReason.text = setScoreStrReason;
            //此处加入toast android原生方法
            toast.InvokeEvent("字符超出规定大小！");
        }
    }





    #endregion


    #region package method

    private void AboutClose()
    {
        aboutPanel.GetComponent<CanvasGroup>()
            .DOFade(.0f, .35f)
            .SetEase(Ease.InOutExpo);
        aboutPanel.transform
        .DOLocalMoveX(720.0f, .35f)
        .OnComplete(() => aboutPanel.SetActive(false));
    }

    private void LookDontOriginalScoreInfoClose()
    {
        lookDontOriginalScoreInfoPanel.GetComponent<CanvasGroup>()
            .DOFade(.0f, .35f)
            .SetEase(Ease.InOutExpo);

        lookDontOriginalScoreInfoPanel.transform
        .DOLocalMoveX(720.0f, .35f)
        .OnComplete(() => lookDontOriginalScoreInfoPanel.SetActive(false));
    }

    private void ReturnLinstener()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (aboutPanel.transform.localPosition.x == .0f) AboutClose();
            else if (lookDontOriginalScoreInfoPanel.transform.localPosition.x == .0f)
                LookDontOriginalScoreInfoClose();
            else
            {
                if (quitCount < 1)
                {
                    toast.InvokeEvent("再按一次退出应用");
                    quitCount++;
                    Invoke("QuitCountDefault", 1.5f);
                }
                else StartCoroutine(Quit());
            }
        }
    }

    private void QuitCountDefault() => quitCount = 0;

    private IEnumerator Quit()
    {
        toast.InvokeEvent("emmm~真的要离开我吗？");

        yield return new WaitForSeconds(.8f);
        Application.Quit();
    }

    private void WriteDontOriginalScoresInfo(string endPath)
    {
        if (!FileExist(endPath))
            File.Create(_startPath + endPath).Dispose();


        string[] persion = File.ReadAllLines(_startPath + endPath);
        string originalStr = File.ReadAllText(_startPath + endPath);
        StringBuilder stringBuilder = new StringBuilder();
        bool canRunDontContains = true;
        for (i = 0; i < persion.Length; i++)
        {
            if(persion[i].Contains(researchStrTemp))
            {
                for (int j = 0; j < persion.Length; j++)
                {
                    if (j != i)
                        stringBuilder.Append(persion[j] + "\n");
                }

                stringBuilder = stringBuilder.Insert(0, $"{System.DateTime.Now} {researchStrTemp}:{JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score}分\n");
                
                File.WriteAllText(_startPath + endPath, stringBuilder.ToString());
                canRunDontContains = false;
            }



            if(!persion[persion.Length - 1].Contains(researchStrTemp) && canRunDontContains && i == persion.Length - 1)
            {
                originalStr = originalStr.Insert(0, $"{System.DateTime.Now} {researchStrTemp}:{JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score}分\n");
                
                File.WriteAllText(_startPath + endPath, originalStr);
            }
        }

        if(persion.Length == 0)
            File.WriteAllText(_startPath + endPath, $"{System.DateTime.Now} {researchStrTemp}:{JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score}分\n");
        
    }


    private void WriteBeforeDontOriginalScoresNowChangedInfo(string endPath)
    {
        string[] persion = File.ReadAllLines(_startPath + endPath);
        StringBuilder stringBuilder = new StringBuilder();
        for (i = 0; i < persion.Length; i++)
        {
            if (persion[i].Contains(researchStrTemp) && JsonTool.GetInstance().ReadFile<OwnInfo>(_startPath + $"/PersionInfos/{ConvertToPinYin(researchStrTemp)}Info.json").score == 800)
            {
                for (int j = 0; j < persion.Length; j++)
                {
                    if (j != i)
                        stringBuilder.Append(persion[j] + "\n");
                }

                File.WriteAllText(_startPath + endPath, stringBuilder.ToString());
            }
        }
    }



    private int GetStrLength(string str)
    {
        if (string.IsNullOrEmpty(str)) return 0;
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        byte[] s = ascii.GetBytes(str);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }
        }
        return tempLen;
    }


    private string ConvertToPinYin(string str)
    {
        string PYstr = "";
        foreach (char item in str.ToCharArray())
        {
            if (ChineseChar.IsValidChar(item))
            {
                ChineseChar cc = new ChineseChar(item);

                //PYstr += string.Join("", cc.Pinyins.ToArray());
                PYstr += cc.Pinyins[0].Substring(0, cc.Pinyins[0].Length - 1);
                //PYstr += cc.Pinyins[0].Substring(0, cc.Pinyins[0].Length - 1).Substring(0, 1).ToLower();
            }
            else
            {
                PYstr += item.ToString();
            }
        }
        return PYstr;
    }

    private RuntimePlatform Platform() => Application.platform;

    private bool FileExist(string path) => File.Exists(_startPath + path);

    private bool DirectoryExist(string path) => Directory.Exists(_startPath + path);


    #endregion
}
